using System;
using System.IO;
using SoftwareMonkeys.Scriptech.Entities;
using SoftwareMonkeys.Scriptech.State;

namespace SoftwareMonkeys.Scriptech.Web.Projections
{
	public class ProjectionMapper
	{
		private string applicationPath = String.Empty;
		public string ApplicationPath
		{
			get {
				if (applicationPath == String.Empty && StateAccess.IsInitialized)
					applicationPath = StateAccess.State.ApplicationPath;
				return applicationPath; }
			set { applicationPath = value; }
		}
		
		public ProjectionMapper ()
		{
		}
		
		public string GetInternalPath(string originalPath)
		{
			string shortPath = GetShortPath(originalPath);
			
			string fileName = Path.GetFileName(shortPath);
			
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
			
			string[] parts = fileNameWithoutExtension.Split('-');
			
			if (parts.Length == 2)
			{
				string typeName = String.Empty;
				string action = String.Empty;
				
				if (EntityState.IsType(parts[1]))
				{
					typeName = parts[1];
					action = parts[0];
				}
				else
				{
					typeName = parts[0];
					action = parts[1];
				}
				
				string format = GetFormat(fileName);
				
				string path = applicationPath + "/Projector.aspx?t=" + typeName + "&a=" + action + "&f=" + format;
				
				return path;
			}
			else
				return String.Empty;
		}                             
		
		public string GetShortPath(string originalPath)
		{
			string shortPath = originalPath;
			
			if (originalPath.IndexOf("?") > -1)
				shortPath = originalPath.Substring(0, originalPath.IndexOf("?"));
			
			return shortPath;
		}
		
		public string GetFormat(string fileName)
		{
			string ext = Path.GetExtension(fileName).Trim('.');
			
			if (ext == "aspx")
				return "Html";
			
			throw new NotSupportedException("Extension not yet supported: " + ext);
		}
	}
}

